import 'dart:convert';

import 'package:gluz/app/data/api_response.dart';
import 'package:gluz/app/utils/toast_util.dart';

import '../../app_session.dart';
import 'network/http_manager.dart';

enum Method { get, post }

/// http请求对业务的包装
class HttpUtil {
  Http http = Http();
  Future<void> setup() async {
    await http.setup();
  }
  Options forceCacheOptions() {
    return http.forceCacheOptions();
  }
  Future<T?> request<T>({
    required String path,
    Method method = Method.get,
    required T Function(dynamic) fromJson,
    dynamic params,
    Options? options,
    String? contentType,
    CancelToken? cancelToken,
  }) async {
    Options? mergeOptions = options?.copyWith(
      headers: {
        'Authorization': 'Bearer ${app.getToken()}',
        'content-language': app.isLangRU() ? 'ru_RU' : 'zh_CN'
      },
    ) ?? Options(
      headers: {
        'Authorization': 'Bearer ${app.getToken()}',
        // 'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjE5NDUzMjAzNjY2Nzc2MTg2OTAsInJuU3RyIjoidDFxcnRJalFqcWtubFhBM0F2SWU5U3l4SFNlV2VwY1kiLCJpZCI6MTk0NTMyMDM2NjY3NzYxODY5MCwiY291bnRyeUNvZGUiOiI4NiIsInBob25lTnVtYmVyIjoiMTU3MTEyNTY2MTQiLCJuaWNrTmFtZSI6IuS4iemUpCIsImFyZWFJZCI6MTIzNCwiYXZhdGFyIjoiaHR0cHM6Ly9nbHV6LW9zcy5vc3MtY24tYmVpamluZy5hbGl5dW5jcy5jb20vdXBsb2Fkcy8yMDI1MDMxOC9mOTg1YjMyZjg5ZGIzNWMwYTAzYjZjZjBiZTgxZmEwOS5qcGVnIiwiaWRlbnRpdHkiOiIxIn0.K34l58nBoTRcQfllvipLRap79ZHSbbjvJm0F1nc-bvk',
        'content-language': app.isLangRU() ? 'ru_RU' : 'zh_CN'
      },
    );
    try {
      dynamic res;
      if (method == Method.get) {
        res = await http.get(
          path,
          params: params,
          options: mergeOptions,
          contentType: contentType,
          cancelToken: cancelToken,
        );
      } else {
        res = await http.post(
          path,
          data: params,
          options: mergeOptions,
          contentType: contentType,
          cancelToken: cancelToken,
        );
      }
      Map<String, dynamic> resMap = {};
      if (res is String) {
        resMap = Map<String, dynamic>.from(jsonDecode(res));
      }
      if (res is Map) {
        resMap = Map<String, dynamic>.from(res);
      }
      if (resMap.isEmpty) {
        logger.e('数据为空');
        return null;
      }

      if (T == ApiResponse) {
        T resObj = fromJson(resMap);
        return resObj;
      } else {
        ApiResponse apiResponse = ApiResponse.fromJson(resMap);
        dynamic apiData = apiResponse.data;
        if (apiData == null) return null;
        if (apiData is String) {
          String dataString = apiData;
          Map<String, dynamic> dataMap = jsonDecode(dataString);
          if (dataMap.isNotEmpty) {
            return fromJson(Map<String, dynamic>.from(dataMap));
          } else {
            return fromJson(dataString);
          }
        } else if (apiData is Map) {
          return fromJson(Map<String, dynamic>.from(apiData));
        } else if (apiData is List) {
          return fromJson(List.from(apiData));
        } else {
          return null;
        }
      }
    } catch (e) {
      ToastUtil.dismiss();
      logger.e(e.toString());
      return null;
    }
  }


  Future<double> getOssImageAspectRatio(String url) async {
    final dio = Dio();
    final response = await dio.get("$url?x-oss-process=image/info");

    if (response.statusCode == 200) {
      final data = jsonDecode(response.data);
      final width = int.parse(data["ImageWidth"]["value"].toString());
      final height = int.parse(data["ImageHeight"]["value"].toString());
      return width.toDouble() / height.toDouble();
    } else {
      throw Exception("获取图片信息失败");
    }
  }
}
